from flask import request
from . import src


@src.route('/services/intent')
def intent_service():

    """
    Triggers the parsing of the intent:// URI scheme
    """

    response = """

        <html>
            <head>
                <meta charset="utf-8" />
                <title>Trigger parseUri()</title>
            </head>
            <body>
                <script>
                    location.href="intent://#Intent;SEL;action=android.intent.action.VIEW;end";
                </script>
            </body>
        </html>

    """

    return response


@src.route('/services/intent/dolphin')
def intent_service_dolphin():

    """
    Triggers the parsing of the intent:// URI scheme
    """

    response = """

        <html>
            <head>
                <meta charset="utf-8" />
                <title>Trigger parseUri()</title>
            </head>
            <body>
                <script>
                    location.href="intent://#Intent;SEL;component=mobi.mgeek.TunnyBrowser/.SetupWizardActivity;action=android.intent.action.VIEW;end";
                </script>
            </body>
        </html>

    """

    return response


@src.route('/services/logcat/<method>', methods=['POST'])
def logcat_service(method):

    """
    CRUD of all logs generated by
    lobotomy's Logcat functionality
    """

    if method == "update":
        if request.form["data"]:
            try:
                # Write Logcat data
                # to logcat.log
                #
                with open("web/app/logs/logcat.log", "w") as log:
                    log.write(request.form["data"])
                    log.close()

                return "Success"

            except IOError as e:

                try:
                    # Write Logcat data
                    # to logcat.log
                    #
                    with open("web/app/logs/flask.log", "w") as log:
                        log.write(e.message)
                        log.close()

                except IOError:
                    # Raise for now
                    # until a logger is implemented
                    raise
                return "Error"
        else:
            return "Error"

